﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.Build.Reporting;
using UnityEditor.Callbacks;
using System;
using System.IO;

public class Builder
{
    class BuildData
    {
        public bool gm = true;
        public bool buildAB = true;
        public bool release = false;
        public bool aab = false;
        public string pathName;
        public string buildFolder;
        public ScriptingImplementation scriptingBackend;
        public void Reset()
        {
            buildAB = true;
            release = false;
            aab = false;
            gm = true;
        }
    }
    static BuildData s_buildData = new BuildData();
    private static readonly string BuildPath = "./Output/";
    [MenuItem("Demo/CI/Android(Debug)")]
    public static void GenAndroidDebug()
    {
        s_buildData.Reset();
        s_buildData.scriptingBackend = ScriptingImplementation.Mono2x;
        DoGenAndroid();
    }
    private static void DoGenAndroid()
    {
        if (EditorUserBuildSettings.activeBuildTarget != BuildTarget.Android)
        {
            EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.Android, BuildTarget.Android);
        }
        if(s_buildData.buildAB)
        {
            //AssetBundleEditor.BuildAssetBundle(BuildTarget.Android);
        }
        PlayerSettings.Android.keystorePass = "xkydwzwn";
        PlayerSettings.Android.keyaliasName = "infinigames";
        PlayerSettings.Android.keyaliasPass = "xkydwzwn";
        PlayerSettings.SetScriptingBackend(BuildTargetGroup.Android, s_buildData.scriptingBackend);
        PlayerSettings.enableCrashReportAPI = false;
        PlayerSettings.stripEngineCode = true;
        PlayerSettings.SetManagedStrippingLevel(BuildTargetGroup.Android, ManagedStrippingLevel.High);
        AndroidArchitecture aac = AndroidArchitecture.ARMv7;
        EditorUserBuildSettings.buildAppBundle = s_buildData.aab;
        if(s_buildData.aab)
        {
            s_buildData.pathName = "{0}.aab";
            EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.Gradle;
        }
        else
        {
            s_buildData.pathName = "{0}.apk";
        }
        if (s_buildData.scriptingBackend == ScriptingImplementation.IL2CPP)
        {
            aac |= AndroidArchitecture.ARM64;
            AddReleaseDefineSymbols();
            RemoveEnableLogDefineSymbols();
        }
        else if (s_buildData.scriptingBackend == ScriptingImplementation.Mono2x)
        {
            RemoveReleaseDefineSymbols();
            s_buildData.pathName = "{0}_Debug.apk";
        }
        PlayerSettings.Android.targetArchitectures = aac;
        BuildPlayerOptions options = new BuildPlayerOptions();
        
        options.scenes = new[] { "Assets/Scenes/Launch.unity"};
        string date = DateTime.Now.ToString("MM_dd_yyyy_HH:mm:ss");
        string folderPath = BuildPath+date;
        if(!Directory.Exists(folderPath))
        {
            Directory.CreateDirectory(folderPath);
        }
        s_buildData.buildFolder = folderPath;
        s_buildData.pathName = string.Format(s_buildData.buildFolder +"/"+ s_buildData.pathName, date);
        options.locationPathName = s_buildData.pathName;
        options.target = BuildTarget.Android;
        if (s_buildData.scriptingBackend == ScriptingImplementation.Mono2x)
        {
            options.options = BuildOptions.Development | BuildOptions.AllowDebugging | BuildOptions.ConnectWithProfiler;
        }
        BuildReport report = BuildPipeline.BuildPlayer(options);
       // System.Diagnostics.Process.Start(BuildPath);
    }
    [PostProcessBuildAttribute(1)]
    public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
    {
        RemoveEnableLogDefineSymbols();
        RemoveReleaseDefineSymbols();
        if(s_buildData.release)
        {
            var path = s_buildData.pathName.Substring(0, s_buildData.pathName.LastIndexOf("."));
            var filename = path.Substring(path.LastIndexOf("/")+1);
            var outputPath = s_buildData.buildFolder;
            string outPath = outputPath + "/libs/";
            FileUtil.CopyFileOrDirectory("Temp/StagingArea/libs", outPath);
            outPath = outputPath+"/il2cppOutput/";
            FileUtil.CopyFileOrDirectory("Temp/StagingArea/Il2Cpp/il2cppOutput", outPath);
            var zipfile= BuildPath+filename+".zip";
            ZipHelper.ZipDirectory(outputPath, zipfile);
            Debug.Log(" outputPath:"+outputPath+" zipfile:"+zipfile);
            if(Directory.Exists(s_buildData.buildFolder))
            {
                Directory.Delete(s_buildData.buildFolder, true);
            }
        }
        System.Diagnostics.Process.Start("Output/");
        Debug.Log("OnPostprocessBuild");
    }
    public static void AddDefineSymbols(string symbols)
    {
        string Settings = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android);
        string release = ";"+symbols;
        if (!Settings.Contains(release))
        {
            Settings = Settings + release;
            PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android, Settings);      
        }
    }
    public static void RemoveDefineSymbols(string symbols)
    {
        string Settings = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android);
        if (Settings.Contains(symbols))
        {
            Settings = Settings.Remove(Settings.IndexOf(symbols, StringComparison.Ordinal), symbols.Length);
            PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android, Settings);
        }
    }
    public static void AddReleaseDefineSymbols()
    {
        AddDefineSymbols("APP_RELEASE");
    }

    public static void RemoveReleaseDefineSymbols()
    {
        RemoveDefineSymbols("APP_RELEASE");
    }
    public static void AddEnableLogDefineSymbols()
    {
        AddDefineSymbols("ENABLE_LOG");
    }
    public static void RemoveEnableLogDefineSymbols()
    {
        RemoveDefineSymbols("ENABLE_LOG");
    }
}
